package org.mineground.listener;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.mineground.Main;
import org.mineground.PermissionNodes;
import org.mineground.player.MinegroundPlayer;

/**
 * @file BlockListener.java (22.01.2012)
 * @author Daniel Koenen
 *
 */
public class BlockListener implements Listener {
    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockBreak(BlockBreakEvent breakEvent) {
        if (breakEvent.isCancelled()) {
            return;
        }
        
        Player eventPlayer = breakEvent.getPlayer();
        
        if (!eventPlayer.hasPermission(PermissionNodes.PERMISSION_ALLOW_BLOCK_BREAK)) {
            breakEvent.setCancelled(true);
            return;
        }
        
        if (!Main.getInstance().containsPlayer(eventPlayer)) {
            breakEvent.setCancelled(true);
            return;
        }
        
        MinegroundPlayer playerInstance = Main.getInstance().getPlayer(eventPlayer);
        
        if (!playerInstance.isLoggedIn()) {
            breakEvent.setCancelled(true);
            return;
        }
        
        playerInstance.addRemovedBlock();
    }
    
    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockBreak(BlockPlaceEvent placeEvent) {
        if (placeEvent.isCancelled()) {
            return;
        }
        
        Player eventPlayer = placeEvent.getPlayer();
        
        if (!eventPlayer.hasPermission(PermissionNodes.PERMISSION_ALLOW_BLOCK_PLACE)) {
            placeEvent.setCancelled(true);
            return;
        }
        
        if (!Main.getInstance().containsPlayer(eventPlayer)) {
            placeEvent.setCancelled(true);
            return;
        }
        
        MinegroundPlayer playerInstance = Main.getInstance().getPlayer(placeEvent.getPlayer());
        
        if (!playerInstance.isLoggedIn()) {
            placeEvent.setCancelled(true);
            return;
        }
        
        playerInstance.addPlacedBlock();
    }
}
